package com.yisu.expressway.download;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;


import com.yisu.expressway.settings.AppGlobalSetting;
import com.yisu.expressway.utils.HBLog;

import java.io.File;

/**
 * 下载事件接收器
 * @author hugh
 * @since 1.2.9
 * @date 16/4/26
 */
public class ApkDownloadReceiver extends BroadcastReceiver {

    public static final String KEY_LAST_DOWNLOAD_ID = "last_download_id";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction() == DownloadManager.ACTION_DOWNLOAD_COMPLETE) {
            AppGlobalSetting mSetting = new AppGlobalSetting(context);
            long refId = mSetting.getLongGlobalItem(KEY_LAST_DOWNLOAD_ID, 0);
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (refId == id) {
                DownloadManager dlMgr = (DownloadManager) context
                        .getSystemService(Context.DOWNLOAD_SERVICE);
                String file = queryDownloadFile(dlMgr, id);
                if (!TextUtils.isEmpty(file)) {
                    instalApk(context, file);
                }
            }
        }
    }

    /**
     * 查询下载完成的文件uri
     *
     * @param dlMgr
     * @param refId
     * @return
     */
    private String queryDownloadFile (DownloadManager dlMgr, long refId) {
        DownloadManager.Query myDownloadQuery = new DownloadManager.Query();
        myDownloadQuery.setFilterById(refId);

        String fileName = "";
        Cursor cursor = dlMgr.query(myDownloadQuery);
        if(cursor != null){
            if (cursor.moveToFirst()) {
                fileName = cursor.getString(cursor.getColumnIndex(
                        DownloadManager.COLUMN_LOCAL_FILENAME));

                HBLog.d(getClass().getSimpleName(), fileName);
            }

            if (!cursor.isClosed()) {
                cursor.close();
            }
        }

        return fileName;
    }

    /**
     * 开始安装
     * @param apkFile
     */
    private void instalApk(Context context, String apkFile) {
        File file = new File(apkFile);
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }
}
